﻿using System;

namespace EPiMVC.Reflection
{
    public static class TypeExtensions
    {
        internal static bool HasAttribute<T>(this Type type) where T : Attribute
        {
            bool typeHasAttribute = false;
            object[] attributes = GetAttributes(type);
            foreach (object attribute in attributes)
            {
                if (typeof(T).IsAssignableFrom(attribute.GetType()))
                    typeHasAttribute = true;
            }

            return typeHasAttribute;
        }

        private static object[] GetAttributes(Type type)
        {
            return type.GetCustomAttributes(true); ;
        }

        internal static T GetAttribute<T>(this Type type) where T : Attribute
        {
            T attribute = null;

            object[] attributes = type.GetCustomAttributes(true);
            foreach (object attributeInType in attributes)
            {
                if (typeof(T).IsAssignableFrom(attributeInType.GetType()))
                    attribute = (T)attributeInType;
            }

            return attribute;
        }
    }
}
